# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1533627595476': {  # dwc 支付宝 限额： 1-3000 整数
        'API_KEY': 'MEYv6TsvAnblSBY9KlffdlEsn9jBsYag',
        'gateway': 'http://pay.55re.cn/pay/gateway',
        'query_gateway': 'http://pay.55re.cn/pay/query',
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pay_type(service):
    if service == 'alipay':
        return 'ali_wap'
    elif service == 'wxpay':
        return 'wx_wap'
    elif service == 'qq':
        return 'qq_wap'
    else:
        return 'bank_pay'


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("jiufutongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')
    p_dict = {
        'down_num': app_id,
        'pay_service': _get_pay_type(service),
        'amount': int(pay_amount * 100),
        'order_down': str(pay.id),
        'subject': 'charge',
        'client_ip': _get_device_ip(info),
        'version': '1.0',
        'callback_url': '{}/pay/api/{}/jiufutongpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'notify_url': '{}/pay/api/{}/jiufutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    j = json.dumps(p_dict)
    _LOGGER.info("jiufutongpay create data: %s", j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=j, headers=headers, timeout=5)
    _LOGGER.info("jiufutongpay create rsp data: %s", response.text)
    # if json.loads(response.text)['pay_info'].startswith('')
    return {'charge_info': json.loads(response.text)['pay_info']}


# success
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    _LOGGER.info("jiufutongpay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, key)
    pay_id = data['order_down']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('jiufutongpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['order_status']
    trade_no = data.get('order_up')
    total_fee = float(data['amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('jiufutongpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'down_num': app_id,
        'order_down': str(pay_id),
        'version': '1.0',
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    j = json.dumps(p_dict)
    _LOGGER.info(u'jiufutongpay query data: %s', j)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=j, headers=headers, timeout=5)
    _LOGGER.info(u'jiufutongpay query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['order_status'])
        total_fee = float(data['amount']) / 100.0
        trade_no = data['order_up']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0、支付失败
        # 1、支付成功
        # 2、下单失败
        # 3、下单成功，等待支付
        # 4、已退款
        if trade_status == 1:
            _LOGGER.info('jiufutongpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jiufutongpay data error, status_code: %s', response.status_code)
